/*
 * @author Alexey Hursevich
 * @version 1.0
 */
package by.bsu.scs.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author Alexey Hursevich
 * @version 1.0
 * 
 * MD5 encryption.
 * 
 */
public class MD5Encoder {

	private static final String ALGORITHM = "MD5";
	private static final String ENCODING = "UTF8";
	private static final String SALT_TEMPLATE = "25,03,11";

	private static MessageDigest messageDigest;
	private static byte salt[];
	
	/**
	 * Encrypts a string using MD5 encryption algorithm.
	 * Method is used in security purposes for storing
	 * user passwords in DB and Cookies.
	 * 
	 * @param toEncrypt input string which should be encrypted by MD5
	 * 
	 * @return value encrypted by MD5
	 */

	public static synchronized String getHash(String toEncrypt) {
		String result = "";
		try {
			if (messageDigest == null) {
				// Singleton initialization
				messageDigest = MessageDigest.getInstance(ALGORITHM);
				
				// MD5 salt initialization
				String salttmp[] = SALT_TEMPLATE.split(",");
				salt = new byte[salttmp.length];
				for (int i = 0; i < salt.length; i++) {
					salt[i] = Byte.parseByte(salttmp[i]);
				}
			} else {
				messageDigest.reset();
			}
			// Add salt
			messageDigest.update(salt);
			messageDigest.update(toEncrypt.getBytes(ENCODING));
			
			//Get encrypted byte array
			byte s[] = messageDigest.digest();
			
			for (int i = 0; i < s.length; i++) { 
				result += Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6); 
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
}
